﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;

namespace frmPrincipal
{
    public partial class frmConPorNome : Form
    {
        private StandardDBConnection standardDBConnection = new StandardDBConnection();
        private string campo;
        private string tabela;

        public frmConPorNome(string lbl, string title, string tabela, string campo, int grdX, int grdY)
        {
            Size grdSize = new Size(grdX, grdY - 70);
            Size frmSize = new Size(grdX + 40, grdY + 50);

            InitializeComponent();

            grdConsultaPorNome.Size = grdSize;
            this.Size = frmSize;            
            
            lblNome.Text = lbl;
            lblNome.Location = new Point(lblNome.Location.X - lblNome.Size.Width, lblNome.Location.Y);            
            txtNome.Width = frmSize.Width - lblNome.Location.X - lblNome.Size.Width - btnSearch.Width - 40;
            btnSearch.Location = new Point(txtNome.Location.X + txtNome.Width + 5, btnSearch.Location.Y);

            this.Text = title;
            this.tabela = tabela;
            this.campo = campo;            

        }

        //Funções Auxiliares
        private void reSize()
        {
            txtNome.Width = this.Size.Width - lblNome.Location.X - lblNome.Size.Width - btnSearch.Width - 40;
            btnSearch.Location = new Point(txtNome.Location.X + txtNome.Width + 5, btnSearch.Location.Y);
            grdConsultaPorNome.Size = new Size(this.Size.Width - 37, this.Size.Height - 120);
        }        

        private void frmConPorNome_Resize(object sender, EventArgs e)
        {
            reSize();
        }
        private void frmConPorNome_FormClosed(object sender, FormClosedEventArgs e)
        {
            standardDBConnection.cnn.Close();
        }

        //Pesquisar por Nome
        private void PesquisarPorNome()
        {
            string sqlCommandText;
            NpgsqlDataAdapter da;
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            sqlCommandText = "SELECT * FROM " + tabela +
                    " WHERE " + campo + " ILIKE '%" + txtNome.Text + "%' " +
                    "ORDER BY " + campo;

            da = new NpgsqlDataAdapter(sqlCommandText, standardDBConnection.cnn);
            ds.Reset();
            da.Fill(ds);
            dt = ds.Tables[0];
            grdConsultaPorNome.DataSource = dt;
            
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            PesquisarPorNome();
        }
        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                PesquisarPorNome();
        }
    }
}
